package com.zhengsr.latte.ec.ec.main.statusbar;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.View;

import com.zhengsr.latte.app.Latte;
import com.zhengsr.latte.ec.R;


/**
 * Created by zhengshaorui on 2018/5/27.
 */

public class TranslucentBehavior extends CoordinatorLayout.Behavior<Toolbar> {
    private static final String TAG = "TranslucentBehavior";

    //注意这个变量一定要定义成类变量
    private int mOffset = 0;
    //延长滑动过程
    private static final int MORE = 100;

    /**
     * 带两个参数的是必须添加的，因为用到了反射
     *
     * @param context
     * @param attrs
     */
    public TranslucentBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Toolbar child, View dependency) {
        return dependency.getId() == R.id.home_rv;
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull Toolbar child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        child.getBackground().setAlpha(0);
        return true;
    }

    @Override
    public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout,
                               @NonNull Toolbar toolbar,
                               @NonNull View target,
                               int dxConsumed,
                               int dyConsumed,
                               int dxUnconsumed,
                               int dyUnconsumed,
                               int type) {
        //super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
        int startOffset = 0;
        Context context = Latte.getApplication();
        int endOffset = context.getResources().getDimensionPixelSize(R.dimen.toolbar_height) + MORE;
        mOffset  += dyConsumed;
        //向上滑
        if (mOffset <= startOffset){
            toolbar.getBackground().setAlpha(0);
        }else if (mOffset > startOffset && mOffset < endOffset){
            final float percent = (float) (mOffset - startOffset)/endOffset;
            final int alpha = (int) (percent * 255);
            toolbar.getBackground().setAlpha(alpha);
        }else{
            toolbar.getBackground().setAlpha(255);
        }
    }
}
